package com.boot.admin.modules.sys.ai.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.boot.admin.core.service.BaseServiceImpl;
import com.boot.admin.modules.sys.ai.mapper.AiMessageMapper;
import com.boot.admin.modules.sys.ai.model.entity.AiMessage;
import com.boot.admin.modules.sys.ai.model.vo.AiMessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI消息服务
 *
 * @author 李飞洋
 * @date 2025/9/24
 */
@Slf4j
@Service
public class AiMessageService extends BaseServiceImpl<AiMessageMapper, AiMessage> {

    /**
     * 获取对话的所有消息
     */
    public List<AiMessageVO> getConversationMessages(String conversationId) {
        return this.baseMapper.getConversationMessages(conversationId);
    }

    /**
     * 获取最近的消息
     */
    public List<AiMessageVO> getRecentMessages(String conversationId, Integer limit) {
        return this.baseMapper.getRecentMessages(conversationId, limit);
    }

    /**
     * 获取下一个消息序号
     */
    public Integer getNextMessageIndex(String conversationId) {
        Integer nextIndex = this.baseMapper.getNextMessageIndex(conversationId);
        return nextIndex != null ? nextIndex : 1;
    }

    /**
     * 保存用户消息
     */
    public AiMessage saveUserMessage(String conversationId, String content, Integer messageIndex) {
        AiMessage message = new AiMessage();
        message.setId(IdUtil.simpleUUID());
        message.setConversationId(conversationId);
        message.setSenderType(1); // 用户
        message.setMessageType(1); // 文本
        message.setContent(content);
        message.setMessageIndex(messageIndex);
        message.setCreated(LocalDateTime.now());
        
        save(message);
        return message;
    }

    /**
     * 保存AI消息
     */
    public AiMessage saveAiMessage(String conversationId, String content, String audioUrl, 
                                   Integer audioDuration, Integer messageIndex) {
        AiMessage message = new AiMessage();
        message.setId(IdUtil.simpleUUID());
        message.setConversationId(conversationId);
        message.setSenderType(2); // AI
        message.setMessageType(1); // 文本
        message.setContent(content);
        message.setAudioUrl(audioUrl);
        message.setAudioDuration(audioDuration);
        message.setMessageIndex(messageIndex);
        message.setCreated(LocalDateTime.now());
        
        save(message);
        return message;
    }
}